<template>
	<div class="tomae-content content-border-bg" :class="{ 'is-expanded': expanded }">
		<el-icon class="cursor-pointer !absolute right-20px top-10px" :size="20" color="#dcdfe6" @click="close"
			style="z-index: 11">
			<Close />
		</el-icon>
		<div style="font-size: 16px; text-align: center; color: #fff; margin-bottom: 10px">
			{{ roadName }}
		</div>
		<!-- 单个路段对比时content-fade-right -->
		<div class="child-box2 congestion-length" style="padding: 70px 0 0">
			<div class="cus-date1">
				<div>选择时间段一</div>
				<div class="date">
					<el-date-picker v-model="timeTow1" type="date" range-separator="至" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" start-placeholder="选择开始日期" end-placeholder="选择结束日期" @change="dataChange" />
				</div>
			</div>

			<div class="cus-date">
				<div>选择时间段二</div>
				<div class="date">
					<el-date-picker v-model="timeTow" type="date" range-separator="至" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" start-placeholder="选择开始日期" end-placeholder="选择结束日期" @change="dataChange" />
				</div>
			</div>
			<!-- <div class="time-group">
        <div class="time-label">分析时段</div>
        <div class="time">
          <el-select v-model="period" placeholder="请选择" @change="changeTable">
            <el-option
              v-for="(item, index) in timeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div> -->

			<div class="title">
				<p>运行情况监测对比统计 </p>
			</div>
			<div class="sub-title">
				<p>拥堵指数对比统计
					<el-radio-group v-model="radio" @change="radioInput">
						<el-radio label="全部"> </el-radio>
						<el-radio label="时间段一"> </el-radio>
						<el-radio label="时间段二"> </el-radio>
					</el-radio-group>
				</p>
			</div>
			<div id="chart5" class="left-chart"></div>
			<div class="sub-title">
				<p>实时速度对比统计</p>
			</div>
			<div id="chart6" class="left-chart"></div>
			<div class="sub-title">
				<p>拥堵里程对比统计</p>
			</div>
			<div id="chart7" class="left-chart"></div>
		</div>
		<!-- 选择本年度时 -->
		<!-- <div v-show="!moonEchart" class="child-box congestion-length content-border-bg">
      <div class="title">
        <p>运行情况监测对比统计</p>
      </div>
      <div class="sub-title">
        <p>本年度拥堵指数对比统计</p>
      </div>
      <div id="chart8" class="left-chart"></div>
      <div class="sub-title">
        <p>本年度实时速度对比统计</p>
      </div>
      <div id="chart9" class="left-chart"></div>
      <div class="sub-title">
        <p>本年度自由流速度对比统计</p>
      </div>
      <div id="chart10" class="left-chart"></div>
      <div class="sub-title">
        <p>本年度拥堵时长对比统计</p>
      </div>
      <div id="chart11" class="left-chart"></div>
    </div> -->
		<!-- <MapBox :pId="1" @handle-emit="handleEmit" style="opacity: 0" /> -->
	</div>
</template>
<script>
	import {
		defineComponent,
		onMounted,
		inject,
		reactive,
		toRefs
	} from 'vue';
	import customDatePicker from '@/components/customDatePicker';
	import {
		selectYdRoadRecord,
		selectYdRoadRecord2
	} from '@/api/tomae';
	import dayjs from 'dayjs';
	export default defineComponent({
		// components: { MapBox },
		props: {
			expanded: {
				type: Boolean,
				default: false,
			},
		},
		components: {
			customDatePicker
		},
		emit: ['update:expanded'],
		setup(props, {
			emit
		}) {
			// var val = localStorage.getItem('mapTrue');
			const state = reactive({
				moonEchart: true,
				datePickerTwo: null,
				chartsType: false,
				radioCurrent: 0,
				xData: [],
				xData1: [],
				xData2: [],
				roadName: '',
				list: [],
				list1: [],
				list2: [],
				firstList: [],
				firstList1: [],
				firstList2: [],
				secondList: [],
				secondList1: [],
				secondList2: [],
				radio: '全部',
				timeTow: '',
				timeTow1: '',
				queryForm: {},
				chart7: null,
				chart6: null,
				chart5: null,
				period: 2,
				roadId: '',
				timeOptions: [{
						label: '整天(00:00 ~ 24:00)',
						value: 0,
					},
					{
						label: '全天(06:00 ~ 22:00)',
						value: 1,
					},
					{
						label: '早平峰(06:00 ~ 07:00)',
						value: 2,
					},
					{
						label: '早高峰(07:00 ~ 09:00)',
						value: 3,
					},
					{
						label: '上午平峰(09:00 ~ 11:00)',
						value: 4,
					},
					{
						label: '午高峰(11:00 ~ 13:00)',
						value: 5,
					},
					{
						label: '下午平峰(13:00 ~ 17:00)',
						value: 6,
					},
					{
						label: '晚高峰(17:00 ~ 19:00)',
						value: 7,
					},
				],
			});
			const init = async (form) => {
				if (form) {
					// state.queryForm = form;
					state.roadName = form.roadName;
					state.radio = '全部';
					state.roadId = form?.roadId;
				}
				console.log(form, '道路点击---');
				// let params = JSON.parse(JSON.stringify(state.queryForm));
				let params = {};
				if ([0, 1, 2].includes(state.radioCurrent)) {
					params.dateTime = state.timeTow1;
					params.compareDateTime = state.timeTow;
					params.type = state.period;
					params.roadId = form?.roadId || state.roadId;
				}
				// console.log("params",params);
				const data = await selectYdRoadRecord2(params);

				const {
					result1,
					result2
				} = data;
				let setDataList = [];
				// 拥挤指数
				state.avgIndex = [
					[],
					[]
				]
				state.avgIndex[0] = result1.map((item) => {
					item = item.avgIndex
					return item
				})
				state.avgIndex[1] = result2.map((item) => {
					item = item.avgIndex
					return item
				})
				state.avgIndex[0][95] = state.avgIndex[0][94]
				state.avgIndex[1][95] = state.avgIndex[1][94]
				// 实时速度
				state.avgSpeed = [
					[],
					[]
				]
				state.avgSpeed[0] = result1.map((item) => {
					item = item.avgSpeed
					return item
				})
				state.avgSpeed[1] = result2.map((item) => {
					item = item.avgSpeed
					return item
				})
				state.avgSpeed[0][95] = state.avgSpeed[0][94]
				state.avgSpeed[1][95] = state.avgSpeed[1][94]
				// 拥挤里程
				state.avgLength = [
					[],
					[]
				]
				state.avgLength[0] = result1.map((item) => {
					item = item.avgLength
					return item
				})
				state.avgLength[1] = result2.map((item) => {
					item = item.avgLength
					return item
				})
				state.avgLength[0][95] = state.avgLength[0][94]
				state.avgLength[1][95] = state.avgLength[1][94]
				if (state.radioCurrent === 1) {
					state.avgIndex[1] = []
					state.avgSpeed[1] = []
					state.avgLength[1] = []
				}
				if (state.radioCurrent === 2) {
					state.avgIndex[0] = []
					state.avgSpeed[0] = []
					state.avgLength[0] = []
				}
				chart5();
				chart6();
				chart7();
			};
			onMounted(() => {
				// let oneWeekStart = dayjs()
				// 	.startOf('w')
				// 	.add(1, 'day')
				// 	.subtract(7, 'day')
				// 	.format('YYYY-MM-DD');
				// let oneWeekEnd = dayjs().startOf('w').add(1, 'day').subtract(1, 'day').format(
				// 	'YYYY-MM-DD');
				// let twoWeekStart = dayjs()
				// 	.startOf('w')
				// 	.add(1, 'day')
				// 	.subtract(14, 'day')
				// 	.format('YYYY-MM-DD');
				// let twoWeekEnd = dayjs().startOf('w').add(1, 'day').subtract(8, 'day').format(
				// 	'YYYY-MM-DD');
				let ddd = [
					dayjs().endOf('day').subtract(1, 'day').format('YYYY-MM-DD'),
					dayjs().endOf('day').format('YYYY-MM-DD'),
				];
				state.timeTow1 = state.timeTow1 || ddd[0]
				state.timeTow = state.timeTow || ddd[1]

			});
			// 获取当前时间
			const getToday = (add) => {
				var date = new Date();
				if (add) {
					date = new Date(date.getTime() + 1000 * 60 * 60 * 24 * add);
				}
				var year = date.getFullYear();
				var dateArr = [
					date.getMonth() + 1,
					date.getDate(),
					date.getHours(),
					date.getMinutes(),
					date.getSeconds(),
				];
				for (var i = 0; i < dateArr.length; i++) {
					if (dateArr[i] >= 1 && dateArr[i] <= 9) {
						dateArr[i] = '0' + dateArr[i];
					}
				}
				var strDate =
					year +
					'-' +
					dateArr[0] +
					'-' +
					dateArr[1] +
					' ' +
					dateArr[2] +
					':' +
					dateArr[3] +
					':' +
					dateArr[4];
				state.today = strDate;
				return state.today;
			};

			const echarts = inject('echarts');

			const radioInput = (val) => {
				if (val == '时间段一') {
					state.radioCurrent = 1;
				} else if (val == '时间段二') {
					state.radioCurrent = 2;
				} else {
					state.radioCurrent = 0;
				}
				init();
			};

			const setLength = (data) => {
				var xlength;
				if (data.length > 7) {
					xlength = parseInt(data.length / 7);
				} else {
					xlength = 0;
				}
				return xlength;
			};
			const chart5 = () => {
				const chart5 = echarts.init(document.getElementById('chart5'));
				const fullXAxis = Array.from({
					length: 95
				}, (_, i) => {
					const hour = Math.floor((i + 1) / 4); // 从第1段（00:15）开始
					const minute = ((i + 1) % 4) * 15; // 分钟计算
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});
				const option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
			              <div>
			                <span style="color:${item.color}">●</span>
			                ${item.seriesName}: ${item.value}
			              </div>
			            `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},
					yAxis: {
						type: 'value',
						interval: 0.5,
						min: 0.5,
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						axisTick: {
							show: false,
						},
						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line',
							name: '时间段一',
							data: state.avgIndex[0] || [],
							lineStyle: {
								color: '#1891FD',
							},
							itemStyle: {
								color: '#1891FD',
							},
						},
						{
							type: 'line',
							name: '时间段二',
							data: state.avgIndex[1] || [],
							lineStyle: {
								color: '#4FD17D',
							},
							itemStyle: {
								color: '#4FD17D',
							},
						},
					],
				};

				chart5.setOption(option);
			};


			const chart6 = () => {
				// 下面一半的不进行展示
				const chart6 = echarts.init(document.getElementById('chart6'));
				const fullXAxis = Array.from({
					length: 95
				}, (_, i) => {
					const hour = Math.floor((i + 1) / 4); // 从第1段（00:15）开始
					const minute = ((i + 1) % 4) * 15; // 分钟计算
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});

				let option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
					      <div>
					        <span style="color:${item.color}">●</span>
					        ${item.seriesName}: ${item.value}
					      </div>
					    `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},

					yAxis: {
						type: 'value',
						name: '单位(km/h)',
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						min: 10,
						axisTick: {
							show: false,
						},

						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line', // 图表类型：折线图
							name: '时间段一', // 数据名称
							data: state.avgSpeed[0], // 第一组数据
							lineStyle: {
								color: '#1891FD', // 折线颜色
							},
							itemStyle: {
								color: '#1891FD', // 数据点颜色
							},
						},
						{
							type: 'line', // 图表类型：折线图
							name: '时间段二', // 数据名称
							data: state.avgSpeed[1], // 第二组数据
							lineStyle: {
								color: '#4FD17D', // 折线颜色
							},
							itemStyle: {
								color: '#4FD17D', // 数据点颜色
							},
						},
					],
				};
				chart6.setOption(option);
			};
			const chart7 = () => {
				// 下面一半的不进行展示
				const chart7 = echarts.init(document.getElementById('chart7'));
				const fullXAxis = Array.from({
					length: 95
				}, (_, i) => {
					const hour = Math.floor((i + 1) / 4); // 从第1段（00:15）开始
					const minute = ((i + 1) % 4) * 15; // 分钟计算
					return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
				});

				let option = {
					title: {
						textStyle: {
							fontSize: 12,
							fontWeight: 400,
						},
						left: 'center',
					},
					legend: {
						data: ['时间段一', '时间段二'],
						right: '40%',
						itemWidth: 6,
						itemGap: 20,
						textStyle: {
							color: '#fff',
						},
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line',
						},
						formatter: (params) => {
							if (params.length > 0) {
								const index = params[0].dataIndex; // 获取数据索引
								const time = fullXAxis[index]; // 对应时间
								let content = `<div>${time}</div>`;
								params.forEach((item) => {
									content += `
					      <div>
					        <span style="color:${item.color}">●</span>
					        ${item.seriesName}: ${item.value}
					      </div>
					    `;
								});
								return content;
							}
							return '';
						},
					},
					grid: {
						top: '17%',
						bottom: '15%',
					},
					xAxis: {
						type: 'category',
						data: fullXAxis,
						axisTick: {
							show: true,
						},
						axisLabel: {
							formatter: (value, index) => (index % 4 === 0 ? value : ''), // 每小时显示一次
							textStyle: {
								color: '#fff',
							},
							fontSize: 12,
							margin: 5,
						},
					},

					yAxis: {
						type: 'value',
						name: '单位(km)',
						nameTextStyle: {
							color: '#fff',
							fontSize: 12,
						},
						axisTick: {
							show: false,
						},

						axisLabel: {
							textStyle: {
								color: '#fff',
							},
						},
						splitLine: {
							show: false,
						},
					},
					series: [{
							type: 'line', // 图表类型：折线图
							name: '时间段一', // 数据名称
							data: state.avgLength[0], // 第一组数据
							lineStyle: {
								color: '#1891FD', // 折线颜色
							},
							itemStyle: {
								color: '#1891FD', // 数据点颜色
							},
						},
						{
							type: 'line', // 图表类型：折线图
							name: '时间段二', // 数据名称
							data: state.avgLength[1], // 第二组数据
							lineStyle: {
								color: '#4FD17D', // 折线颜色
							},
							itemStyle: {
								color: '#4FD17D', // 数据点颜色
							},
						},
					],
				};

				chart7.setOption(option);
			};
			const close = () => {
				emit('update:expanded', false);
			};
			const dataChange = () => {
				init();
			};
			const changeTable = () => {
				init();
			};
			return {
				...toRefs(state),
				radioInput,
				init,
				chart5,
				chart6,
				chart7,
				close,
				dataChange,
				changeTable,
			};
		},
	});
</script>
<style lang="less" scoped>
	.tomae-content {
		position: absolute;
		left: 100%;
		top: 3%;
		width: 30%;
		height: 95%;
		z-index: 3;
		transition: transform 0.6s;
		transform: translateX(0);
		padding: 10px 0;

		&.is-expanded {
			transform: translateX(calc(-100% - 30px));
		}
	}

	.element::-webkit-scrollbar {
		width: 0 !important;
	}

	.child-box {
		width: 100%;
		height: 100%;
		overflow: auto;
		overflow-x: hidden;

		.title {
			width: 100%;
			height: 42px;
			display: flex;
			align-items: center;
			background: url(@/assets/images/report/leftTitle.png) no-repeat;

			p {
				font-size: 20px;
				color: white;
				margin-left: 30px;
				font-weight: 400;
			}
		}

		.left-chart {
			height: 200px;
			width: 100%;
			z-index: 800;
		}
	}

	.child-box2 {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		padding-top: 40px;

		.title {
			width: 100%;
			height: 42px;
			margin-left: 40px;
			display: flex;
			align-items: center;
			background: url(@/assets/images/report/leftTitle.png) no-repeat;
			margin-bottom: 10px;

			p {
				font-size: 20px;
				color: white;
				margin-left: 30px;
				font-weight: 400;
			}
		}

		.left-chart {
			height: 28%;
			width: 100%;
			margin: 10px 0;
			z-index: 800;
		}
	}

	.cus-date,
	.cus-date1 {
		position: absolute;
		top: 40px;
		left: 40px;
		right: 0;
		z-index: 9;
		display: flex;
		align-items: center;
		color: rgba(3, 123, 255, 1);

		.date {
			border: 1px solid rgba(3, 123, 255, 1);
			border-radius: 4px;
			margin-left: 10px;
		}
	}

	.cus-date {
		color: greenyellow;
		margin-bottom: 10px;
	}

	.cus-date1 {
		top: 0;
	}

	.time-group {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin: 10px 0;
		color: #fff;

		.time-label {
			color: #999;
			// margin-right: 10px;
			width: 84px;
		}

		.time {
			width: 350px;

			.el-select {
				width: 100%;
			}
		}
	}

	.sub-title {
		background: url(@/assets/images/report/leftSubTitle.png) no-repeat;
		width: 87%;
		height: 25px;

		p {
			margin-left: 21px;
			color: white;
			font-size: 16px;
			position: relative;
			top: -7px;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}
</style>